package com.uxsino.simo.connections;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public abstract class AbstractConnection<TargetType> implements IConnection<TargetType> {

    private static final Logger logger = LoggerFactory.getLogger(AbstractConnection.class);

    protected boolean connected;

    protected int state;//0 失败， 1 成功

    protected Map<Integer, String> states;

    protected TargetType target;

    public AbstractConnection() {
        states = new HashMap<Integer, String>();
    }

    @Override
    public int connect(TargetType target) {
        this.target = target;
        ConnectionCleaner.push(this);
        return 0;
    }

    @Override
    public int getState() {
        return state;
    }

    @Override
    public String getStateName(int stateValue) {
        return states.get(stateValue);
    }

    @Override
    public boolean isConnected() {
        return connected;
    }

    @Override
    public void setConnected(boolean connectde) {
        connected = connectde;
    }

    @Override
    public boolean connectAndTest(TargetType target, String cmdString, String resStart) {
        boolean result = false;
        try{
        connect(target);
        if (connected) {
            result = testWithConnected(cmdString, resStart);
        }
        }catch (Exception e){
            throw e;
        }finally {
            try {
                this.close();
            }catch (Exception ee){
                logger.error("close test connection error: ", ee);
            }
        }
        return result;
    }

    @Override
    public boolean testWithConnected(String cmdString, String resStart) {
        return connected;
    }

    public boolean testConnCache(String cmdString, String resStart) {
        if (connected) {

        }
        return false;
    }
    @Override
    public int close() {
        ConnectionCleaner.remove(this);
        return 0;
    }
}
